package net.cyue.ort.llm.gui.state;

import net.cyue.ort.llm.LLMClient;
import net.cyue.ort.llm.generator.GenerationConfig;
import net.cyue.ort.llm.template.ModelChatMessage;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 应用运行时状态，集中管理模型、生成参数与会话上下文，
 * 便于在不同UI组件之间共享且保持线程安全。
 */
public class AppState implements AutoCloseable {

    private final AtomicReference<LLMClient> llmClient = new AtomicReference<>();
    private final AtomicReference<GenerationConfig> generationConfig = new AtomicReference<>();
    private final AtomicBoolean generating = new AtomicBoolean(false);
    private final List<ModelChatMessage> history =
            Collections.synchronizedList(new ArrayList<>());

    public Optional<LLMClient> getLlmClient() {
        return Optional.ofNullable(llmClient.get());
    }

    public void setLlmClient(LLMClient newInstance) {
        LLMClient previous = llmClient.getAndSet(newInstance);
        if (previous != null && previous != newInstance) {
            previous.close();
        }
    }

    public Optional<GenerationConfig> getGenerationConfig() {
        return Optional.ofNullable(generationConfig.get());
    }

    public void setGenerationConfig(GenerationConfig config) {
        generationConfig.set(config);
    }

    public boolean hasModelLoaded() {
        return llmClient.get() != null && generationConfig.get() != null;
    }

    public boolean startGeneration() {
        return generating.compareAndSet(false, true);
    }

    public void finishGeneration() {
        generating.set(false);
    }

    public List<ModelChatMessage> getHistory() {
        return history;
    }

    public void resetHistory() {
        synchronized (history) {
            history.clear();
        }
    }

    @Override
    public void close() {
        LLMClient instance = llmClient.getAndSet(null);
        if (instance != null) {
            instance.close();
        }
    }
}

